package com.ludomancy.selbst;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Arc2D;

public class Opportunity
{
	private double angle;
	private int distance;
	private double powerFeed = 0;
	private double power = 50; // initial power
	private double decay = 0.2; // amount of power it consumes per turn
	private final double MAX_RADIUS = 40;
	private final double MAX_POWER = 150;
	private final long UPDATE_TIME = 5; // once each 10 milliseconds
	private long lastUpdateTime;
	
	public Opportunity(double angle, int distance)
	{
		this.angle = angle;
		this.distance = distance;
		lastUpdateTime = System.currentTimeMillis();
	}
	
	public void paint(Graphics g)
	{
		Graphics2D g2 = (Graphics2D) g;
		g2.setColor(Color.BLUE);
		Arc2D.Double ellipse = new Arc2D.Double(getLocalPosition().x-getRadius()/2, getLocalPosition().y-getRadius()/2, getRadius(), getRadius(), 0, 360, Arc2D.PIE);
		g2.fill(ellipse);
	}
	
	public Point getLocalPosition()
	{
		int x = (int)(Math.cos(angle) * distance);
		int y = (int)(Math.sin(angle) * distance);
		return new Point(x,y);
	}
	
	private int getRadius()
	{
		return (int)((MAX_RADIUS * power)/MAX_POWER);
	}

	public boolean isWithin(Point cursor)
	{
		Point position = getLocalPosition();
		int deltaX = (cursor.x-position.x)*(cursor.x-position.x);
		int deltaY = (cursor.y-position.y)*(cursor.y-position.y);
		double sqrt = Math.sqrt(deltaX + deltaY); 
		return sqrt <= getRadius()/2;
	}

	public double getPowerFeed()
	{
		return powerFeed;
	}
	
	public void setPowerFeed(double amount)
	{
		powerFeed = amount;
	}

	public void removePowerFeed(double amount)
	{
		powerFeed = Math.max(0, powerFeed - amount);
	}
	
	public void run()
	{
		if(System.currentTimeMillis() - lastUpdateTime > UPDATE_TIME)
		{
			power += powerFeed;
			power -= decay;
			power = Math.max(0, power);
			power = Math.min(power, MAX_POWER);
			lastUpdateTime = System.currentTimeMillis();
		}
	}

	public boolean isGone()
	{
		return power <= 0;
	}
}
